<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <el-tab-pane name="role" label="角色管理">
            <el-row type="flex" align="middle" style="height:60px">
              <el-button type="primary" size="small" icon="el-icon-plus" @click="addRoleWindow">新增角色</el-button>
            </el-row>
            <el-table
              :data="roleList"
              stripe
              style="width: 100%"
            >
              <el-table-column label="序号" width="180">
                <template slot-scope="scope">
                  {{ scope.$index+1 }}
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="角色名"
                width="180"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-setting" @click="editPermissionDialog(scope.row.id)">分配权限</el-button>
                  <el-button type="warning" icon="el-icon-edit" @click="editRole(scope.row.id)">修改角色</el-button>

                  <el-button type="danger" icon="el-icon-delete" @click="delRole(scope.row.id)">删除角色</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex" justify="end" align="middle" style="height: 60px;">
              <el-pagination
                layout="prev, pager, next,sizes,total"
                :total="total"
                :page-size="pageSetting.pagesize"
                :page-sizes="[2,5,10]"
                @size-change="changeSize"
                @current-change="changePage"
              />
            </el-row>
            <!-- 添加角色的窗口 -->
            <el-dialog :title="title" :visible="showDialog" width="50%" @close="closeWindow">
              <el-form ref="roleForm" :model="roleFormData" :rules="rules">
                <el-form-item label="角色名称" label-width="120px" prop="name">
                  <el-input v-model="roleFormData.name" autocomplete="off" placeholder="请输入2-10位任意字符" />
                </el-form-item>
                <el-form-item label="角色描述" label-width="120px" prop="description">
                  <el-input v-model="roleFormData.description" autocomplete="off" placeholder="请输入5-50位任意字符" />
                </el-form-item>

              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="closeWindow">取 消</el-button>
                <el-button type="primary" @click="ok">确 定</el-button>
              </div>
            </el-dialog>
            <!-- 分配权限窗口 -->
            <PermissionDialog :id="roleId" ref="PermissionDialog" :show-permission-dialog.sync="showPermissionDialog" />
          </el-tab-pane>
          <!-- 公司信息 -->
          <el-tab-pane name="company" label="公司信息">
            <el-row type="flex" justify="center">
              <el-alert
                title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
                type="warning"
                :show-icon="true"
                :closable="false"
                style="width:800px"
              />
            </el-row>
            <el-row type="flex" justify="center">
              <el-form label-position="left" label-width="120px" style="margin-top:50px">
                <el-form-item label="企业名称">
                  <el-input v-model="companyDetail.name" disabled style="width: 400px" />
                </el-form-item>
                <el-form-item label="公司地址">
                  <el-input v-model="companyDetail.companyAddress" disabled style="width: 400px" />
                </el-form-item>
                <el-form-item label="公司电话">
                  <el-input v-model="companyDetail.companyPhone" disabled style="width: 400px" />
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="companyDetail.mailbox" disabled style="width: 400px" />
                </el-form-item>
                <el-form-item label="备注">
                  <el-input v-model="companyDetail.remarks" disabled style="width: 400px" />
                </el-form-item>
              </el-form>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getRoleList, delRole, addRole, getRoleDetail, updateRole, getCompanyDetail } from '@/api/setting'
import { mapGetters } from 'vuex'
import PermissionDialog from './component/PermissionDialog.vue'
export default {
  components: {
    PermissionDialog
  },
  data() {
    const validRoleName = async(rules, value, callback) => {
      const { rows: list } = await getRoleList()
      if (this.roleFormData.id) {
        list.some(item => item.name === value && this.roleFormData.id !== item.id) ? callback(new Error('已存在相同的角色')) : callback()
      } else {
        list.some(item => item.name === value) ? callback(new Error('已存在相同的角色')) : callback()
      }
    }
    return {
      showPermissionDialog: false,
      roleId: '',
      activeName: 'role',
      roleList: [],
      total: 0,
      pageSetting: {
        page: 1,
        pagesize: 2
      },
      companyDetail: {},
      showDialog: false,
      roleFormData: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, trigger: 'blur', message: '角色名称不能为空！' },
          { min: 2, max: 10, trigger: 'blur', message: '请输入2-10位任意字符！' },
          { validator: validRoleName, trigger: 'blur' }
        ],
        description: [
          { required: true, trigger: 'blur', message: '角色描述不能为空！' },
          { min: 5, max: 50, trigger: 'blur', message: '请输入5-50位任意字符！' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['companyId']),
    title() {
      return this.roleFormData.id ? '编辑角色' : '新增角色'
    }
  },
  watch: {
  // 本来watch 是要数据发生变化时才会触发
    // 我希望页面一进来不管数据会不会变都会触发
    // 1. 别的页面跳进来 id 不变
  // 2. 当前页面刷新, id 会从无到有
    companyId: {
      handler(value) {
        if (this.companyId) {
          // 判断当前的 companyId 是否存在
          // 如果在则发请求
          this.getCompanyDetail()
        }
      },
      immediate: true
    }
  },
  created() {
    this.getRoleList()
    // 一刷新本页面  companyId还没有拿到  所以不要在创建生命周期调用
    // this.getCompanyDetail()
  },
  methods: {
    // 显示分配权限的窗口
    async editPermissionDialog(id) {
      this.roleId = id
      await this.$refs.PermissionDialog.getPermissionList()
      await this.$refs.PermissionDialog.getRoleDetail()
      this.showPermissionDialog = true
    },
    // 获取角色名称
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageSetting)
      this.roleList = rows
      this.total = total
      // console.log(this.total)
    },
    // 删除角色
    delRole(roleId) {
      this.$confirm('是否删除该角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRole(roleId)
        this.$message.success('删除成功')
        this.getRoleList()
      }).catch(() => {
        // 取消删除操作
      })
    },
    // 点击确认按钮  进行新增或者编辑
    async ok() {
      try {
        const isValid = await this.$refs.roleForm.validate()
        if (isValid) {
          // 根据id判断当前状态是修改还是新增
          if (this.roleFormData.id) {
            await updateRole(this.roleFormData)
            this.$message.success('修改成功！')
          } else {
            await addRole(this.roleFormData)
            this.$message.success('新增成功！')
          }

          this.closeWindow()
          this.getRoleList()
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 弹出新增窗口
    addRoleWindow() {
      this.showDialog = true
    },
    // 弹出编辑窗口
    async editRole(roleId) {
      const data = await getRoleDetail(roleId)
      this.roleFormData = data
      this.showDialog = true
    },
    // 关闭窗口
    closeWindow() {
      this.roleFormData = {
        name: '',
        description: ''
      }
      // 这个 reset 只能清理表单有绑定的数据
      // 回显时添加的属性就没办法了
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 获取公司信息
    async getCompanyDetail() {
      this.companyDetail = await getCompanyDetail(this.companyId)
      // console.log(this.companyDetail, '公司信息')
    },
    // 每页显示条数变化触发的函数
    changeSize(curSize) {
      this.pageSetting.pagesize = curSize
      this.getRoleList()
    },
    changePage(curPage) {
      this.pageSetting.page = curPage
      this.getRoleList()
    }
  }
}
</script>

<style lang="sass" scoped>

</style>
